'''
Created on Jun 12, 2012

@author: thomas_dao
'''

from web import base
from web.base import BaseHandler
from web import urls
from web import util
import json
import logging
from google.appengine.ext import ndb
from entity.entity import Poll, Event
from app.query import poll_async

class CreateHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):
        poll = Poll()
        poll.author = util.get_current_user_key()
        poll.question = self.request.params.get('question')
        # Remeber to use int to create key
        event_id = self.request.params.get('event_id')
        poll.event = ndb.Key(Event, int(event_id))
        poll.put()
        # Return the id back to client
        self.response.write(json.dumps(util.ndb_to_dict(poll)))
        

class ReadHandler(BaseHandler):
    def get(self):
        poll_id = self.request.params.get('poll_id')
        poll_key = ndb.Key("Poll", int(poll_id))
        # Return the id back to client
        self.response.write(json.dumps(util.ndb_to_dict(poll_key.get())))
        

class UpdateHandler(BaseHandler):
    def post(self):
        pass
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass    


class AllPollsHandler(BaseHandler):
    @ndb.synctasklet
    def get(self, event_id):
        event_key = ndb.Key(Event, int(event_id))
        polls, options, users = yield poll_async.get_by_event(event_key)
        poll_list = []
        for i in xrange(0, len(polls)):
            poll_dict = util.ndb_to_dict(polls[i])  
            
            option_list = []
            for option in options[i]:
                option_dict = util.ndb_to_dict(option)
                option_dict['users'] = util.ndb_to_list(users[i])
                option_list.append(option_dict)
            
            poll_dict['options'] = option_list
            poll_list.append(poll_dict)    
            
        # Return the id back to client
        self.response.write(json.dumps(poll_list))
        
    
app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()